package com.zlzvip.android.common.http.qiniu;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.picture.picker.release.SelectAlbumActivity;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.SLog;

import java.io.File;
import java.lang.ref.SoftReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.pachong.android.framework.picture.picker.Constants.Constants.IntentExtra.INTENT_SELECTED_PICTURE;

/**
 * 选取图片的辅助类
 * 1. 弹出图片选择框
 * 2. 选中图片后自动上传处理，以及成功失败处理
 * 3. 图片选中上传成功之后给user提供回调
 *
 * 使用方法：
 *  1. 创建对象，并且传递回调
 *  2. user需要在onActivityResult中调用本类的onActivityResult
 *  3. user必须实现接口：ActivityCompat.OnRequestPermissionsResultCallback，
 *  然后在onRequestPermissionsResult 中调用此类的 onRequestPermissionsResult
 *  4. 调用addTargetView方法设置关联的View
 *
 * @Author: Weiwei Peng
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017/1/17 14:01
 * @Version: 1.0.0
 */
public class PictureChooseHelper {


    private SoftReference<AppCompatActivity> mActivityRef;

    public PictureChooseHelper(AppCompatActivity activity,
                               OnPictureReturnSuccessListener successListener,
                               OnPictureReturnFailureListener failureListener) {
        mActivityRef = new SoftReference<>(activity);
        this.pictureReturnSuccessListener = successListener;
        this.pictureReturnFailureListener = failureListener;
    }

    private AppCompatActivity getActivity() {
        return mActivityRef.get();
    }

    private static final int MAXNUM_SELECTPIC = 8;

    private static final int PERMISSIONS_REQUEST_TAKE_PHOTO = 1;
    private static final int PERMISSIONS_REQUEST_CHOSE_PHOTO = 2;

    private static final int TAKE_PHOTO_IMAGE = 201;
    private static final int PICK_UP_IMAGE = 202;

    private List<View> targetViews = new ArrayList<>();
    private View currView;

    public void addTargetView(View view) {
        targetViews.add(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currView = view;
                addPicture(view);
            }
        });

    }

    private void addPicture(final View clickedView) {
        final String[] actionArr = new String[]{"拍照", "从相册中选择"};
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
                                  @Override
                                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                      switch (position) {
                                          case 0:
                                              takePhoto();
                                              break;

                                          case 1:
                                              choosePhoto();
                                              break;
                                      }
                                      diaFrag.dismiss();
                                  }
                              },
                actionArr).show(getActivity().getSupportFragmentManager());

    }


    void takePhoto() {
        // 需要申请的权限
        List<String> needPermissions = new ArrayList<String>();
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            needPermissions.add(Manifest.permission.CAMERA);
        }

        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            needPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (needPermissions.size() > 0) {
            String[] needPerArray = needPermissions.toArray(new String[needPermissions.size()]);
            ActivityCompat.requestPermissions(getActivity(), needPerArray,
                    PERMISSIONS_REQUEST_TAKE_PHOTO);

        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            mTakePhotoUri = createNewPictureUri(getActivity());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            getActivity().startActivityForResult(intent, TAKE_PHOTO_IMAGE);
        }
    }

    private Uri createNewPictureUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(FileManager.getImagePath(context) + File.separator + "IMG_" + timeStamp + ".jpg");
        return Uri.fromFile(mediaFile);
    }

    void choosePhoto() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            EasyToast.showToast(getActivity(), "权限还没有授予");
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSIONS_REQUEST_CHOSE_PHOTO);
        } else {
            Intent intent = new Intent(getActivity(), SelectAlbumActivity.class);
            intent.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
            intent.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, MAXNUM_SELECTPIC);
            getActivity().startActivityForResult(intent, PICK_UP_IMAGE);
        }
    }


    private Uri mTakePhotoUri;
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (currView == null) {
            // 没有被选中的view
            return;
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PHOTO_IMAGE) {
                String imgUrl = mTakePhotoUri.toString();
                QiniuFileUploader.uploadFile(getActivity(), imgUrl, new DataRequestListener<String>(String.class) {
                    @Override
                    public void onSuccess(String url) {
                        super.onSuccess(url);
                        if (pictureReturnSuccessListener != null) {
                            pictureReturnSuccessListener.OnPictureReturnSuccess(currView, url);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        if (pictureReturnFailureListener != null) {
                            pictureReturnFailureListener.OnPictureReturnFailure(currView, t, errorNo, strMsg);
                        }
                    }
                });

            } else if (requestCode == PICK_UP_IMAGE) {
                String mHeadUrl = data.getExtras().getStringArrayList(INTENT_SELECTED_PICTURE).get(0);
                File file = new File(mHeadUrl);
                if (file.exists()) {
                    SLog.e(mHeadUrl + " file exist");
                }
                QiniuFileUploader.uploadFile(getActivity(), mHeadUrl, new DataRequestListener<String>(String.class) {
                    @Override
                    public void onSuccess(String url) {
                        super.onSuccess(url);
                        if (pictureReturnSuccessListener != null) {
                            pictureReturnSuccessListener.OnPictureReturnSuccess(currView, url);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        if (pictureReturnFailureListener != null) {
                            pictureReturnFailureListener.OnPictureReturnFailure(currView, t, errorNo, strMsg);
                        }
                    }
                });

            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == PERMISSIONS_REQUEST_TAKE_PHOTO) {
            if (acceptAllPermissions(permissions, grantResults)) {
                takePhoto();
            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }


        if (requestCode == PERMISSIONS_REQUEST_CHOSE_PHOTO) {
            if (acceptAllPermissions(permissions, grantResults)) {
                choosePhoto();
            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    boolean acceptAllPermissions(String[] permissions, int[] grantResults) {
        if (grantResults != null && grantResults.length > 0) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }

        return true;
    }

    public OnPictureReturnSuccessListener pictureReturnSuccessListener;
    public OnPictureReturnFailureListener pictureReturnFailureListener;

    public interface OnPictureReturnSuccessListener {
        void OnPictureReturnSuccess(View srcView, String url);
    }

    public interface OnPictureReturnFailureListener {
        void OnPictureReturnFailure(View srcView, Throwable t, int errorNo, String strMsg);
    }

}
